package edu.spec.student.service.impl;

import edu.spec.student.dao.iface.ILessonDao;
import edu.spec.student.dao.iface.IStudentDao;
import edu.spec.student.dao.iface.IStudentLessonDao;
import edu.spec.student.model.Student;
import edu.spec.student.model.lesson.Lesson;
import edu.spec.student.model.lesson.StudentLesson;
import edu.spec.student.service.iface.ILessonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by MadFrog on 2017/10/13.
 */
@Service
public class LessonService implements ILessonService {

    @Autowired
    private ILessonDao lessonDao;
    @Autowired
    private IStudentDao studentDao;
    @Autowired
    private IStudentLessonDao studentLessonDao;

    @Override
    public void add(Lesson lesson) {
        // 增加Lesson
        // 根据clazzId，获取全部学生
        // 增加StudentLesson
        Lesson dbLesson = lessonDao.add(lesson);
        List<Student> studentList = new ArrayList<>();
        String[] clazzIds = lesson.getClazzIds().split(",");
        for(int i=0; i<clazzIds.length; i++){
            int clazzId = Integer.parseInt(clazzIds[i]);
            List<Student> sList = studentDao.listStudentByClazz(clazzId);
            studentList.addAll(sList);
        }
        for (Student s : studentList){
            StudentLesson sl = new StudentLesson();
            sl.setLesson(dbLesson);
            sl.setStudent(s);
            sl.setSignIn(0);
            studentLessonDao.add(sl);
        }
    }

    @Override
    public void delete(Integer lessonId) {
        // 删除关联的StudentLesson
        studentLessonDao.deleteByLesson(lessonId);
        // 删除lessonId
        lessonDao.delete(lessonId);
    }

    @Override
    public void update(Lesson lesson) {
        Lesson dbLesson = lessonDao.load(lesson.getId());
        dbLesson.setCourse(lesson.getCourse());
        dbLesson.setClazzIds(lesson.getClazzIds());
        dbLesson.setClazzNames(lesson.getClazzNames());
        dbLesson.setClazzRoom(lesson.getClazzRoom());
        dbLesson.setStartTime(lesson.getStartTime());
        dbLesson.setStatus(lesson.getStatus());
        lessonDao.update(lesson);
    }

    @Override
    public Lesson load(Integer lessonId) {
        return lessonDao.load(lessonId);
    }

    @Override
    public List<Lesson> listLessonByCourse(Integer courseId) {
        return lessonDao.listLessonByCourse(courseId);
    }
}
